package com.example.qzzm;

import java.util.ArrayList;

import com.example.application.QZApplication;
import com.example.constant.App;
import com.example.exception.NotSignInException;
import com.example.jx.JsonUtils;
import com.example.net.Client;
import com.example.qzzm.R;
import com.example.view.GifView;
import com.example.view.MScrollView;
import com.example.view.MScrollView.OnScrollChangerListener;
import com.example.vo.DMessage;
import com.example.vo.Detail;
import com.example.vo.MPicture;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.viewpager.SlideShowView;
import com.viewpager.SlideShowView.ViewPagerItemCLickListener;

import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

/**
 * 详情页面的Activity
 * 
 * @author Administrator
 *
 */
public class XQActivity extends Activity {
	// 返回按钮
	private ImageView ivBack;

	// 图片组
	private SlideShowView isImages;
	// 地图按钮
	private ImageView ivMap;

	// 详细内容
	private MScrollView scDetail;
	// 价格内容
	private LinearLayout lyPrice;
	// 价格内容1
	private LinearLayout lyPrice1;
	// 详情ID
	private String id;
	// 数据
	private Detail detail;
	// 视图
	private GifView gvLoad;
	private TextView tvPrice;
	private TextView tvPrice1;
	private TextView tvTitle;
	private TextView tvTicket;
	private TextView tvOrgPrice;
	private TextView tvOrgPrice1;
	private TextView tvQbuy;
	private TextView tvQbuy1;
	private TextView tvActivity;
	private TextView tvValidTime;
	private TextView tvUseTime;
	private TextView tvAddress;
	private TextView tvBusInfo;
	private TextView tvJoinNum;
	// 地图坐标
	private double lat = 32.043005;
	private double lon = 118.7677;
	// lyPrice
	private int lyPriceY;
	private int scY;
	//
	private boolean isFirst = true;

	private QZApplication application;

	// Handler
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			switch (msg.what) {
			case 0:
				gvLoad.setVisibility(View.VISIBLE);
				scDetail.setVisibility(View.GONE);
				break;
			case 1:
				scDetail.setVisibility(View.VISIBLE);
				gvLoad.setVisibility(View.GONE);
				break;
			default:
				break;
			}

		}
	};

	public ArrayList<String> pic_list = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);
		application = (QZApplication) getApplication();

		initView();
		initListeners();

		Bundle bundle = getIntent().getExtras();
		if (!bundle.containsKey("itemId")) {
			finish();
		}
		id = bundle.getString("itemId");
		FirstTask fTask = new FirstTask();
		fTask.execute();
	}

	// 初始化布局控件
	private void initView() {
		ivBack = (ImageView) findViewById(R.id.iv_back);
		ivMap = (ImageView) findViewById(R.id.iv_map);
		tvPrice = (TextView) findViewById(R.id.tv_price);
		tvPrice1 = (TextView) findViewById(R.id.tv_price1);
		tvTitle = (TextView) findViewById(R.id.tv_title);
		tvTicket = (TextView) findViewById(R.id.tv_ticket);
		tvOrgPrice = (TextView) findViewById(R.id.tv_org_price);
		tvOrgPrice1 = (TextView) findViewById(R.id.tv_org_price1);
		tvQbuy = (TextView) findViewById(R.id.tv_qbuy);
		tvQbuy1 = (TextView) findViewById(R.id.tv_qbuy1);
		tvActivity = (TextView) findViewById(R.id.tv_activity);
		tvValidTime = (TextView) findViewById(R.id.tv_valid_time);
		tvUseTime = (TextView) findViewById(R.id.tv_use_time);
		tvAddress = (TextView) findViewById(R.id.tv_address);
		tvBusInfo = (TextView) findViewById(R.id.tv_bus_info);
		tvJoinNum = (TextView) findViewById(R.id.tv_join_num);
		scDetail = (MScrollView) findViewById(R.id.sc_detail);
		lyPrice = (LinearLayout) findViewById(R.id.ly_price);
		lyPrice1 = (LinearLayout) findViewById(R.id.ly_price1);
		lyPrice1.setVisibility(View.GONE);
		isImages = (SlideShowView) findViewById(R.id.iv_image);

		gvLoad = (GifView) findViewById(R.id.gv_load);
		gvLoad.setMovieResource(R.raw.app_loading);
		gvLoad.setVisibility(View.GONE);
	}

	// 初始化监听事件
	private void initListeners() {
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		ivMap.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(XQActivity.this, MapActivity.class);
				Bundle bundle = new Bundle();
				bundle.putDouble("locationX", lat);
				bundle.putDouble("locationY", lon);
				intent.putExtras(bundle);

				startActivity(intent);
			}
		});

		ViewPagerItemCLickListener listener = new ViewPagerItemCLickListener() {

			@Override
			public void onItemClick(View pager, int position) {
				Intent intent = new Intent();
				intent.setClass(XQActivity.this, ImgActivity.class);
				Bundle bundle = new Bundle();
				bundle.putStringArrayList("imgs", pic_list);
				intent.putExtras(bundle);
				startActivity(intent);
			}

		};
		isImages.setOnItemClickListener(listener);

		scDetail.setOnScrollChangedListener(new OnScrollChangerListener() {

			@Override
			public void onScrollChanged(MScrollView view, int x, int y,
					int oldX, int oldY) {
				if (isFirst) {
					// 第一次判断头部的高度
					int location1[] = new int[2];
					scDetail.getLocationOnScreen(location1);
					scY = location1[1];
					isFirst = false;
				}
				int location[] = new int[2];
				lyPrice.getLocationOnScreen(location);
				lyPriceY = location[1];
				int cha = (lyPriceY - scY);
				if (cha < 0) {
					lyPrice1.setVisibility(View.VISIBLE);
				} else {
					lyPrice1.setVisibility(View.GONE);
				}
			}
		});

		tvQbuy.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					application.getUserId();
				} catch (NotSignInException e) {
					startActivity(new Intent(XQActivity.this,
							LoginActivity.class));
				}
			}
		});
		tvQbuy1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					application.getUserId();
				} catch (NotSignInException e) {
					startActivity(new Intent(XQActivity.this,
							LoginActivity.class));
				}
			}
		});

	}

	// 分享功能-友盟
	@SuppressWarnings("unused")
	private void shareData(String str) {
		// 首先在您的Activity中添加如下成员变量
		final UMSocialService mController = UMServiceFactory
				.getUMSocialService("com.umeng.share");
		// 设置分享内容
		String appID = "wx967daebe835fbeac";
		String appSecret = "5fa9e68ca3970e87a1f83e563c8dcbce";
		// 添加微信平台
		// UMWXHandler wxHandler = new UMWXHandler(this,appID,appSecret);
		// wxHandler.addToSocialSDK();
		// 添加微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(this, appID, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();

		// 设置微信好友分享内容
		WeiXinShareContent weixinContent = new WeiXinShareContent();
		// 设置分享文字
		weixinContent.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能，微信");
		// 设置title
		weixinContent.setTitle("友盟社会化分享组件-微信");
		// 设置分享内容跳转URL
		weixinContent.setTargetUrl("http://www.baidu.com");
		// weixinContent.setShareImage("http://bbs.umeng.com/template/yudi_moji/style/logo.png");
		mController.setShareContent("adashiuashdhausd");
		mController.setShareMedia(weixinContent);
		mController.postShare(XQActivity.this, SHARE_MEDIA.WEIXIN,
				new SnsPostListener() {
					@Override
					public void onStart() {
						Toast.makeText(XQActivity.this, "开始分享.",
								Toast.LENGTH_SHORT).show();
					}

					@Override
					public void onComplete(SHARE_MEDIA arg0, int arg1,
							SocializeEntity arg2) {
						if (arg1 == 200) {
							Toast.makeText(XQActivity.this, "分享成功.",
									Toast.LENGTH_SHORT).show();
						} else {
							String eMsg = "";
							if (arg1 == -101) {
								eMsg = "没有授权";
							}
							Toast.makeText(XQActivity.this,
									"分享失败[" + arg1 + "] " + eMsg,
									Toast.LENGTH_SHORT).show();
						}

					}
				});
	}

	class FirstTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			// 开始执行
			handler.sendEmptyMessage(0);
			// 网络访问，获取列表数据
			Client client = application.getClient();
			String result = client.getResquest(App.DETAIL_URL + id);
			if (result != null) {
				detail = JsonUtils.paraseJson(result, DMessage.class).getData();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// 执行成功

			tvTitle.setText(detail.getName());
			tvTicket.setText(detail.getA_name());
			tvPrice.setText(detail.getReal_price());
			tvOrgPrice.setText("原价: " + detail.getOrg_price() + "元");
			tvPrice1.setText(detail.getReal_price());
			tvOrgPrice1.setText("原价: " + detail.getOrg_price() + "元");
			tvOrgPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);// 删除线
			tvOrgPrice1.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);// 删除线
			tvActivity.setText(Html.fromHtml(detail.getContent()));
			tvValidTime.setText(detail.getEnd_dated());
			tvUseTime.setText(detail.getEnd_month());
			tvAddress.setText(Html.fromHtml(detail.getAddress()));
			tvBusInfo.setText(Html.fromHtml(detail.getBus()));
			tvJoinNum.setText(String.valueOf(detail.getHas_num()));

			lat = Double.valueOf(detail.getLat());
			lon = Double.valueOf(detail.getLon());

			pic_list = new ArrayList<String>();
			for (MPicture mp : detail.getPics()) {
				pic_list.add(mp.getUrl());
			}
			isImages.setImagePath(pic_list);

			// 初始化
			handler.sendEmptyMessage(1);
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// 更新
			super.onProgressUpdate(values);
		}

	}

}
